package com.syh.jn.scm.domain.supplier.entity.sale;

import cn.redscarf.commons.spring.SpringContextUtils;
import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.util.other.ExtAssert;
import cn.redscarf.commons.util.validator.ValidationUtils;
import cn.redscarf.commons.wrapper.Restrictions;
import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.domain.AbstractSimpleAggregate;
import com.syh.core.ddd.domain.CodeExpEnum;
import com.syh.core.ddd.domain.CodeGenerateUtil;
import com.syh.jn.scm.domain.supplier.entity.finance.OrderExpensesBill;
import com.syh.jn.scm.domain.supplier.entity.finance.OrderExpensesBillItem;
import com.syh.jn.scm.domain.supplier.entity.logistics.LogisticsBill;
import com.syh.jn.scm.domain.supplier.entity.logistics.LogisticsBillItem;
import com.syh.jn.scm.domain.supplier.repository.finance.OrderExpensesBillReadRepository;
import com.syh.jn.scm.domain.supplier.repository.finance.OrderExpensesBillRepository;
import com.syh.jn.scm.domain.supplier.repository.logistics.LogisticsBillReadRepository;
import com.syh.jn.scm.domain.supplier.repository.purchase.PurchaseOrderReadRepository;
import com.syh.jn.scm.dto.supplier.sale.SaleOrderMto;
import com.syh.jn.scm.dto.supplier.sale.SaleOrderSto;
import com.syh.jn.scm.dto.support.FilesDto;
import com.syh.jn.scm.exception.BusinessException;
import com.syh.jn.scm.service.api.supplier.finance.enums.OrderExpensesBillEnums;
import com.syh.jn.scm.service.api.supplier.logistics.enums.LogisticsBillEnums;
import com.syh.jn.scm.service.api.supplier.purchase.enums.PurchaseOrderEnums;
import com.syh.jn.scm.service.api.supplier.sale.enums.SaleOrderEnums;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 销售单聚合
 */
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class SaleOrder extends AbstractSimpleAggregate<Long> {


  /**
   * 供应商创建新订单
   *
   * @return
   */
  public static SaleOrder created(SaleOrderSto sto) {
    ExtAssert.notNull(sto, "对象为空");
    ValidationUtils.validate(sto);

    SaleOrder order = SaleOrder.initSaleOrder();
    order.setCode(CodeGenerateUtil.codeGenerate(CodeExpEnum.SALES_ORDER_EXP.getCodeExp(), sto.getDownStreamCompanyId()));
    ExtBeanUtils.copyProperties(sto, order, false);

    //添加订单项
    ExtAssert.notNull(sto.getItems(), "销售明细对象为空");
    order.items = new ArrayList<>();
    sto.getItems().stream().forEach(item -> {
      ValidationUtils.validate(item);
      order.addItem(new SaleOrderItem(item));
    });
    //计算订单总额
    order.calculateTotalAmount();
    return order;
  }

  /*
   * 初始化订单字段
   */
  private static SaleOrder initSaleOrder() {
    SaleOrder order = new SaleOrder();
    order.id = SaleOrder.nextLongId();
    order.ordState = SaleOrderEnums.State.STAYCONFIRM.getStatus();
    order.createTimeStamp = System.currentTimeMillis();
    order.discount = BigDecimal.ZERO;//设置优惠减免的默认值为0
    order.totalFreight = BigDecimal.ZERO;//设置运费总额的默认值为0
    order.deliveryState = SaleOrderEnums.DeliveryState.LOGISTICS_UN_DELIVERY.getStatus();
    order.generatedState = SaleOrderEnums.GeneratedState.LOGISTICS_UN_GENERATE.getStatus();
    order.collectState = SaleOrderEnums.CollectState.LOGISTICS_UN_COLLECT.getStatus();
    return order;
  }


  /**
   * 修改订单
   *
   * @param mto
   */
  public void modify(SaleOrderMto mto) {
    ExtAssert.notNull(mto, "对象为空");
    //只有待确认的订单才能修改
    if (!this.getOrdState().equals(SaleOrderEnums.State.STAYCONFIRM.getStatus())) {
      throw new BusinessException("订单不是待确认状态,不可以修改");
    }
    this.lastUpdateTimeStamp = System.currentTimeMillis();
    ExtBeanUtils.copyProperties(mto, this, false);

    this.items = new ArrayList<>();
    ExtAssert.notNull(mto.getItems(), "销售明细对象为空");
    mto.getItems().stream().forEach(item -> {
      ValidationUtils.validate(item);
      this.addItem(new SaleOrderItem(item));
    });
    this.calculateTotalAmount();
  }

  /**
   * 增加订单项
   *
   * @param item
   * @return
   */
  public SaleOrder addItem(SaleOrderItem item) {
    if (this.items == null) {
      this.items = new ArrayList<>();
    }
    this.items.add(item);
    return this;
  }

  /**
   * 删除订单,先删除对应的订单项
   */
  public void destroy() {
    //只有订单状态为待确认或者已取消的才能删除
    if (!this.ordState.equals(SaleOrderEnums.State.STAYCONFIRM.getStatus())
            && !this.ordState.equals(SaleOrderEnums.State.CANCEL.getStatus())) {
      throw new BusinessException("订单不是待确认或已取消状态,不可以删除");
    }
    if (this.haveRecord != null &&
            this.haveRecord.equals(SaleOrderEnums.State.HAVE_RECORD.getStatus())) {
      throw new BusinessException("订单已存在记录,不可以删除");
    }
  }

  /**
   * 删除订单项
   *
   * @param item
   * @return
   */
  public SaleOrder removeItem(SaleOrderItem item) {
    this.items.removeIf((innerItem) -> {
      return innerItem.getId().equals(item.getId());
    });
    return this;
  }

  /**
   * 计算订单总额、商品总额
   */
  private void calculateTotalAmount() {
    BigDecimal totalAmount = BigDecimal.valueOf(0);
    for (SaleOrderItem item : this.items) {
      totalAmount = totalAmount.add(item.getTotalAmount());
    }
    this.goodsTotalAmount = totalAmount;//商品总额
    this.totalAmount = totalAmount;//订单总额
    //优惠减免
    if (this.discount != null) {
      this.totalAmount = this.totalAmount.subtract(this.discount);
    }
    if (this.orderExpensesBillId != null) {
      //把其他费用计算入总额
      this.totalAmount = this.totalAmount.add(this.otherExpenses);
    }
  }

  /**
   * 计算订单出库总额、商品出库总额
   */
  private void calculateTotalOutAmount() {
    //计算订单已出库商品总额
    BigDecimal totalAmount = BigDecimal.ZERO;
    for (SaleOrderItem item : this.items) {
      totalAmount = totalAmount.add(item.calculateTotalOutAmount());
    }
    this.totalOutGoodsAmount = totalAmount;

    //先计算出该订单下已发出、已签收状态的物流单据的物流费用
    LogisticsBillReadRepository logisticsBillReadRepository = (LogisticsBillReadRepository) SpringContextUtils.getBean(LogisticsBillReadRepository.class);
    Wrapper we = Wrapper.build();
    we.append(Restrictions.eq("orderId", this.id));
    we.append(Restrictions.eq("orderType", LogisticsBillEnums.OrderType.SALE.getStatus()));
    we.append(Restrictions.or(Restrictions.eq("logisticsState", LogisticsBillEnums.State.DELIVEED.getStatus()),
            Restrictions.eq("logisticsState", LogisticsBillEnums.State.SIGNIN.getStatus())));
    List<LogisticsBill> logisticsBills = logisticsBillReadRepository.getList(we);

    BigDecimal logisticsBillBeforeBuyFreight = BigDecimal.ZERO;//物流单据为预收买家的所有物流费用
    for (LogisticsBill logisticsBill : logisticsBills) {
      boolean justDo = logisticsBill.getFreightTake() != null
              && logisticsBill.getFreightTake().equals(LogisticsBillEnums.FreightTake.BUY.getStatus())
              && logisticsBill.getFreightType().equals(LogisticsBillEnums.FreightType.BEFORE.getStatus());
      if (justDo) {
        logisticsBillBeforeBuyFreight = logisticsBillBeforeBuyFreight.add(logisticsBill.getTotalFreight());
      }
    }

    //计算订单发货总额
    if (this.discount != null) {
      totalAmount = totalAmount.subtract(this.discount);
    }
    totalAmount = totalAmount.add(logisticsBillBeforeBuyFreight);
    if (this.orderExpensesBillId != null) {
      //加入其他订单费用
      totalAmount = totalAmount.add(this.otherExpenses);
    }
    this.totalOutAmount = totalAmount.compareTo(BigDecimal.ZERO) < 1 ? BigDecimal.ZERO : totalAmount;
    this.totalFreight = logisticsBillBeforeBuyFreight;
    this.lastUpdateTimeStamp = System.currentTimeMillis();
  }

  /*
   * 计算订单发货状态
   */
  private void calculateDeliveryStatus() {
    this.deliveryState = SaleOrderEnums.DeliveryState.LOGISTICS_WHOLE_DELIVEED.getStatus();
    //默认标记为未发货
    boolean unDelivery = true;

    //计算订单发货状态
    for (SaleOrderItem item : this.items) {
      //订单项已发货数量小于订单数量则为部分发货
      if (this.deliveryState.equals(SaleOrderEnums.DeliveryState.LOGISTICS_WHOLE_DELIVEED.getStatus())
              && item.getOutedQuantity().compareTo(item.getQuantity()) < 0) {
        this.deliveryState = SaleOrderEnums.DeliveryState.LOGISTICS_PART_DELIVEED.getStatus();
      }
      //订单项已发货数量大于0 则不是未发货
      if (unDelivery && item.getOutedQuantity().compareTo(BigDecimal.ZERO) > 0) {
        unDelivery = false;
      }
    }
    if (unDelivery) {
      this.deliveryState = SaleOrderEnums.DeliveryState.LOGISTICS_UN_DELIVERY.getStatus();
      this.deliveryTimestamp = null;
    }
  }

  /**
   * 确认,只有待确认的订单才能确认
   */
  public void confirm() {
    if (!this.getOrdState().equals(SaleOrderEnums.State.STAYCONFIRM.getStatus())) {
      throw new BusinessException("订单不是待确认状态,不可以确认");
    }
    this.ordState = SaleOrderEnums.State.CONFIRM.getStatus();
  }

  /**
   * 取消订单，只有待确认的订单才能取消
   */
  public void cancel() {
    if (!this.getOrdState().equals(SaleOrderEnums.State.STAYCONFIRM.getStatus())) {
      throw new BusinessException("订单不是待确认状态,不可以取消");
    }
    this.ordState = SaleOrderEnums.State.CANCEL.getStatus();
  }

  /**
   * 取消确认订单，只有已确认的订单才能取消
   */
  public void cancelConfirm() {
    if (!this.getOrdState().equals(SaleOrderEnums.State.CONFIRM.getStatus())) {
      throw new BusinessException("订单不是确认状态,不可以取消确认");
    }
    LogisticsBillReadRepository logisticsBillReadRepository = (LogisticsBillReadRepository) SpringContextUtils.getBean(LogisticsBillReadRepository.class);
    Wrapper we = Wrapper.build().append(Restrictions.eq("orderId", this.id))
            .append(Restrictions.eq("orderType", LogisticsBillEnums.OrderType.SALE.getStatus()));
    if (logisticsBillReadRepository.getCount(we) > 0) {
      throw new BusinessException("订单已生成物流单,不可以取消确认");
    }
    PurchaseOrderReadRepository purchaseOrderReadRepository = (PurchaseOrderReadRepository) SpringContextUtils.getBean("purchaseOrderRepositoryImpl");
    Wrapper purWe = Wrapper.build().append(Restrictions.eq("salesOrderId", this.id)).append(Restrictions.ne("ordState", PurchaseOrderEnums.OrdState.CANCEL.getStatus()));
    //如果已生成直采直销单 则不能取消确认
    if (purchaseOrderReadRepository.getCount(purWe) > 0) {
      throw new BusinessException("订单已生成直采直销单,不可以取消确认");
    }
    this.ordState = SaleOrderEnums.State.STAYCONFIRM.getStatus();
  }

  /**
   * 确认下游收货
   */
  public void confirmReceipt() {
    //计算下游收货金额
    BigDecimal totalInAmount = BigDecimal.valueOf(0);
    for (SaleOrderItem item : this.items) {
      totalInAmount = totalInAmount.add(item.getInTotalAmount());
    }
    this.totalInGoodsAmount = totalInAmount;
    this.totalInAmount = totalInAmount.subtract(this.discount);
  }

  /**
   * 记录已生成物流数量
   *
   * @param logisticsBill
   * @param operate       (1为增加记录，2为减少记录)
   */
  public void countGeneratedQuantity(LogisticsBill logisticsBill, int operate) {
    if (operate == 1) {
      logisticsBill.getItems().forEach(logisticsBillItem -> {
        this.items.forEach(orderItem -> {
          if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
            orderItem.setGeneratedQuantity(orderItem.getGeneratedQuantity() == null ? logisticsBillItem.getQuantity() :
                    orderItem.getGeneratedQuantity().add(logisticsBillItem.getQuantity()));
          }
        });
      });
    } else {
      logisticsBill.getItems().forEach(logisticsBillItem -> {
        this.items.forEach(orderItem -> {
          if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
            orderItem.setGeneratedQuantity(orderItem.getGeneratedQuantity().subtract(logisticsBillItem.getQuantity()));
          }
        });
      });
    }

    //默认为已完全生成物流单
    this.generatedState = SaleOrderEnums.GeneratedState.LOGISTICS_WHOLE_GENERATE.getStatus();
    //默认标记为未生成物流单
    boolean unGenerated = true;

    for (SaleOrderItem item : this.items) {
      //订单项已生成数量小于订单数量则为部分生成物流单
      if (this.generatedState.equals(SaleOrderEnums.GeneratedState.LOGISTICS_WHOLE_GENERATE.getStatus())
              && item.getGeneratedQuantity().compareTo(item.getQuantity()) < 0) {
        this.generatedState = SaleOrderEnums.GeneratedState.LOGISTICS_PART_GENERATE.getStatus();
      }
      //订单项已发货数量大于0 则不是未发货
      if (unGenerated && item.getGeneratedQuantity().compareTo(BigDecimal.ZERO) > 0) {
        unGenerated = false;
      }
    }
    if (unGenerated) {
      this.generatedState = SaleOrderEnums.GeneratedState.LOGISTICS_UN_GENERATE.getStatus();
    }
  }

  /**
   * 发货信息更新
   */
  public void delivery(LogisticsBill bill) {
    //如果是直采直销单 则不检查是否为完全发货
    if (bill.getSubjectBillId() == null) {
      if (this.deliveryState.equals(SaleOrderEnums.DeliveryState.LOGISTICS_WHOLE_DELIVEED.getStatus())) {
        throw new BusinessException("发货失败，已全部发货！");
      }
    }
    //获取物流单据明细并计算订单项的已发货数量
    bill.getItems().forEach(logisticsBillItem -> {
      this.items.forEach(orderItem -> {
        if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
          orderItem.setOutedQuantity(orderItem.getOutedQuantity() == null ? logisticsBillItem.getQuantity() :
                  orderItem.getOutedQuantity().add(logisticsBillItem.getQuantity()));
        }
      });
    });

    this.haveRecord = SaleOrderEnums.State.HAVE_RECORD.getStatus();
    this.deliveryTimestamp = System.currentTimeMillis();
    this.calculateTotalOutAmount();
    this.calculateDeliveryStatus();
  }

  /**
   * 取消发货信息更新
   */
  public void cancelDelivery(LogisticsBill bill) {
    if (this.deliveryState.equals(SaleOrderEnums.DeliveryState.LOGISTICS_UN_DELIVERY.getStatus())){
      throw new BusinessException("取消发货失败，无发货记录！");
    }
    //获取物流单据明细并重新计算订单项的已发货数量
    bill.getItems().forEach(logisticsBillItem -> {
      this.items.forEach(orderItem -> {
        if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
          orderItem.setOutedQuantity(orderItem.getOutedQuantity().subtract(logisticsBillItem.getQuantity()));
        }
      });
    });
    this.calculateTotalOutAmount();
    this.calculateDeliveryStatus();
  }

  /**
   * 生成对账单
   *
   * @param statementOfAccountId
   */
  public void generating(Long statementOfAccountId) {
    if (this.collectState.equals(SaleOrderEnums.CollectState.LOGISTICS_UN_COLLECT.getStatus())) {
      throw new BusinessException("销售单" + this.code + "未签收，无法生成对账单");
    }
    if (this.ordState.equals(SaleOrderEnums.State.STATEMENT.getStatus())) {
      throw new BusinessException("销售单已生成对账单!");
    }
    //如果有订单费用表
    if (this.orderExpensesBillId != null) {
      OrderExpensesBillReadRepository orderExpensesBillRepository = (OrderExpensesBillReadRepository) SpringContextUtils.getBean(OrderExpensesBillRepository.class);
      OrderExpensesBill orderExpensesBill = orderExpensesBillRepository.getById(this.orderExpensesBillId);
      //如果订单费用未确认 不允许生成对账单
      if (!orderExpensesBill.getState().equals(OrderExpensesBillEnums.State.CONFIRM.getStatus())) {
        throw new BusinessException("销售单" + this.code + "生成的费用表未确认。无法生成对账单！");
      }
    }
    this.statementId = statementOfAccountId;
    this.ordState = SaleOrderEnums.State.STATEMENT.getStatus();
  }

  /**
   * 取消对账单
   */
  public void cancelGenerating() {
    if (this.ordState.equals(SaleOrderEnums.State.CONFIRM.getStatus())) {
      throw new BusinessException("销售单已取消对账单!");
    }
    this.statementId = null;
    this.ordState = SaleOrderEnums.State.CONFIRM.getStatus();
  }

  /**
   * 销售订单上传图片
   *
   * @param dto
   */
  public void upload(FilesDto dto) {
    this.mainSrcImages = dto.getFiles();
  }

  /**
   * 纠正订单物流相关字段数据（在订单项outedQuantity和inQuantity字段数据正确的情况下）
   *
   * @param logisticsBillItems
   */
  public void correctingLogisticsData(List<LogisticsBillItem> logisticsBillItems) {
    //订单项generateQuantity字段初始为已发货数量
    this.items.forEach(item -> {
      item.setGeneratedQuantity(item.getOutedQuantity() == null ? BigDecimal.ZERO : item.getOutedQuantity());
      //添加未发货物流订单项商品数量
      logisticsBillItems.forEach(logisticsBillItem -> {
        if (item.getId().equals(logisticsBillItem.getOrderItemId())) {
          item.setGeneratedQuantity(item.getGeneratedQuantity().add(logisticsBillItem.getQuantity()));
        }
      });
    });
    //默认为已完全签收
    this.collectState = SaleOrderEnums.CollectState.LOGISTICS_WHOLE_COLLECT.getStatus();
    //默认标记为未签收
    boolean unCollected = true;
    this.deliveryState = SaleOrderEnums.DeliveryState.LOGISTICS_WHOLE_DELIVEED.getStatus();
    //默认标记为未发货
    boolean unDelivery = true;
    //默认为已完全生成物流单
    this.generatedState = SaleOrderEnums.GeneratedState.LOGISTICS_WHOLE_GENERATE.getStatus();
    //默认标记为未生成物流单
    boolean unGenerated = true;

    for (SaleOrderItem item : this.items) {
      //订单项已生成数量小于订单数量则为部分生成物流单
      if (this.collectState.equals(SaleOrderEnums.CollectState.LOGISTICS_WHOLE_COLLECT.getStatus())
              && (item.getInQuantity() == null || item.getInQuantity().compareTo(item.getQuantity()) < 0)) {
        this.collectState = SaleOrderEnums.CollectState.LOGISTICS_PART_COLLECT.getStatus();
      }
      //订单项已发货数量大于0 则不是未发货
      if (unCollected && (item.getInQuantity() != null && item.getInQuantity().compareTo(BigDecimal.ZERO) > 0)) {
        unCollected = false;
      }
      //订单项已发货数量小于订单数量则为部分发货
      if (this.deliveryState.equals(SaleOrderEnums.DeliveryState.LOGISTICS_WHOLE_DELIVEED.getStatus())
              && (item.getOutedQuantity() == null || item.getOutedQuantity().compareTo(item.getQuantity()) < 0)) {
        this.deliveryState = SaleOrderEnums.DeliveryState.LOGISTICS_PART_DELIVEED.getStatus();
      }
      //订单项已发货数量大于0 则不是未发货
      if (unDelivery && (item.getOutedQuantity() != null && item.getOutedQuantity().compareTo(BigDecimal.ZERO) > 0)) {
        unDelivery = false;
      }
      //订单项已生成数量小于订单数量则为部分生成物流单
      if (this.generatedState.equals(SaleOrderEnums.GeneratedState.LOGISTICS_WHOLE_GENERATE.getStatus())
              && item.getGeneratedQuantity().compareTo(item.getQuantity()) < 0) {
        this.generatedState = SaleOrderEnums.GeneratedState.LOGISTICS_PART_GENERATE.getStatus();
      }
      //订单项已发货数量大于0 则不是未发货
      if (unGenerated && item.getGeneratedQuantity().compareTo(BigDecimal.ZERO) > 0) {
        unGenerated = false;
      }
    }
    if (unCollected) {
      this.collectState = SaleOrderEnums.CollectState.LOGISTICS_UN_COLLECT.getStatus();
    }
    if (unDelivery) {
      this.deliveryState = SaleOrderEnums.DeliveryState.LOGISTICS_UN_DELIVERY.getStatus();
    }
    if (unGenerated) {
      this.generatedState = SaleOrderEnums.GeneratedState.LOGISTICS_UN_GENERATE.getStatus();
    }
  }

  /**
   * 保存订单费用表
   *
   * @param orderExpensesBillId
   */
  public void addExpensesBill(Long orderExpensesBillId) {
    if (this.ordState.equals(SaleOrderEnums.State.STATEMENT.getStatus())) {
      throw new BusinessException("销售单已生成对账单！保存失败！");
    }
    if (this.orderExpensesBillId != null && !this.orderExpensesBillId.equals(orderExpensesBillId)) {
      throw new BusinessException("销售单已有费用表！保存失败！");
    }
    this.orderExpensesBillId = orderExpensesBillId;
    this.otherExpenses = BigDecimal.ZERO;
  }

  /**
   * 删除订单费用表
   *
   * @param orderExpensesBillId
   */
  public void deletedExpensesBill(Long orderExpensesBillId) {
    if (this.ordState.equals(SaleOrderEnums.State.STATEMENT.getStatus())) {
      throw new BusinessException("销售单已生成对账单！创建失败！");
    }
    if (!this.orderExpensesBillId.equals(orderExpensesBillId)) {
      throw new BusinessException("销售单与费用表不匹配！删除失败！");
    }
    this.orderExpensesBillId = null;
  }

  /**
   * 确认订单费用
   *
   * @param orderExpensesBill
   */
  public void confirmExpensesBill(OrderExpensesBill orderExpensesBill) {
    //如果销售单未生成记录(即未发过货) 不允许确认费用
    if (!this.haveRecord.equals(SaleOrderEnums.State.HAVE_RECORD.getStatus())) {
      throw new BusinessException("销售单未发过货！确认费用失败！");
    }
    if (this.ordState.equals(SaleOrderEnums.State.STATEMENT.getStatus())) {
      throw new BusinessException("销售单已生成对账单！确认费用失败！");
    }
    if (!this.orderExpensesBillId.equals(orderExpensesBill.getId())) {
      throw new BusinessException("销售单与费用表不匹配！确认费用失败！");
    }
    this.countExpenses(orderExpensesBill);
  }

  /**
   * 取消订单费用
   *
   * @param orderExpensesBill
   */
  public void cancelExpensesBill(OrderExpensesBill orderExpensesBill) {
    if (this.ordState.equals(SaleOrderEnums.State.STATEMENT.getStatus())) {
      throw new BusinessException("销售单已生成对账单！创建失败！");
    }
    if (!this.orderExpensesBillId.equals(orderExpensesBill.getId())) {
      throw new BusinessException("销售单与费用表不匹配！取消费用失败！");
    }
    this.otherExpenses = BigDecimal.ZERO;
    this.calculateTotalAmount();
    this.calculateTotalOutAmount();
  }

  /**
   * 把其他费用算入订单总额
   */
  private void countExpenses(OrderExpensesBill orderExpensesBill) {
    this.otherExpenses = BigDecimal.ZERO;
    if (orderExpensesBill.getItems() != null) {
      for (OrderExpensesBillItem expensesBillItem : orderExpensesBill.getItems()) {
        //计算纳入总额费用
        if (expensesBillItem.getIncludeTotalAmount().equals(OrderExpensesBillEnums.IncludeTotalAmount.INCLUDE.getStatus())) {
          this.otherExpenses = this.otherExpenses.add(expensesBillItem.getExpenses());
        }
      }
    }
    //重新计算订单总额
    this.calculateTotalAmount();
    //如果已发货
    if (!this.deliveryState.equals(SaleOrderEnums.DeliveryState.LOGISTICS_UN_DELIVERY.getStatus())) {
      //重新计算订单发货总额
      this.calculateTotalOutAmount();
    }
  }

  /**
   * 创建退货单 记录退货数量
   *
   * @param returnOrder 退货单
   */
  public void createdReturnOrder(SaleReturnOrder returnOrder) {
    this.addGeneratedReturnQuantity(returnOrder);
  }

  /**
   * 修改退货单 记录退货数量
   *
   * @param returnOrder    退货单
   * @param oldReturnOrder 旧退货单
   */
  public void updatedReturnOrder(SaleReturnOrder returnOrder, SaleReturnOrder oldReturnOrder) {
    this.subGeneratedReturnQuantity(oldReturnOrder);
    this.addGeneratedReturnQuantity(returnOrder);
  }

  /**
   * 取消退货单 记录退货数量
   *
   * @param returnOrder 退货单
   */
  public void cancelReturnOrder(SaleReturnOrder returnOrder) {
    this.subGeneratedReturnQuantity(returnOrder);
  }

  /**
   * 添加退货数量
   *
   * @param returnOrder
   */
  private void addGeneratedReturnQuantity(SaleReturnOrder returnOrder) {
    returnOrder.getItems().forEach(returnOrderItem -> {
      this.items.forEach(orderItem -> {
        if (orderItem.getId().equals(returnOrderItem.getOrderItemId())) {
          //记录退货数量
          orderItem.setGeneratedReturnQuantity(orderItem.getGeneratedReturnQuantity() == null ? returnOrderItem.getReturnQuantity() : orderItem.getGeneratedReturnQuantity().add(returnOrderItem.getReturnQuantity()));
          //判断退货数量是否大于签收数量
          if (orderItem.getGeneratedReturnQuantity().compareTo(orderItem.getInQuantity()) > 0) {
            BigDecimal returnQuantity = orderItem.getGeneratedReturnQuantity().subtract(returnOrderItem.getReturnQuantity());
            throw new BusinessException("退货数量不能大于签收数量！" + orderItem.getGoodsName() + "已签收" + orderItem.getInQuantity() + " 已生成退货：" + returnQuantity);
          }
        }
      });
    });
  }

  /**
   * 减少退货数量
   *
   * @param returnOrder
   */
  private void subGeneratedReturnQuantity(SaleReturnOrder returnOrder) {
    returnOrder.getItems().forEach(returnOrderItem -> {
      this.items.forEach(orderItem -> {
        if (orderItem.getId().equals(returnOrderItem.getOrderItemId())) {
          //回退退货数量
          orderItem.setGeneratedReturnQuantity(orderItem.getGeneratedReturnQuantity().subtract(returnOrderItem.getReturnQuantity()));
          //判断回退后的数量是否小于0  正常情况不应该小于0
          if (orderItem.getGeneratedReturnQuantity().compareTo(BigDecimal.ZERO) < 0) {
            throw new BusinessException("服务异常，请联系客服！");
          }
        }
      });
    });
  }

  /**
   * 销售订单编号
   */
  private String code;
  /**
   * 第三方订单号
   */
  private String extCode;
  /**
   * 销售订单状态(0：待确认 1：已确认 2：挂起 3：已生成对账单 -1：已取消)
   */
  private Short ordState;
  /**
   * 订单创建类型( 0：服务商录入 1:客户录入 2：对接客户系统 3：系统自动)
   */
  private Short createdType;
  /**
   * 客户id
   */
  private Long downStreamCompanyId;
  /**
   * 归属id
   */
  private Long businessEntityId;
  /**
   * 订单备注
   */
  private String remark;
  /**
   * 优惠金额
   */
  private BigDecimal discount;
  /**
   * 订单总额
   */
  private BigDecimal totalAmount;
  //TODO 下游收货总额字段预计以后要删除
  /**
   * 下游收货总额
   */
  private BigDecimal totalInAmount;
  //TODO 下游收货商品总额字段预计以后要删除
  /**
   * 下游收货商品总额
   */
  private BigDecimal totalInGoodsAmount;
  /**
   * 出库总额
   */
  private BigDecimal totalOutAmount;
  /**
   * 出库商品总额
   */
  private BigDecimal totalOutGoodsAmount;
  /**
   * 运费金额
   */
  private BigDecimal totalFreight;
  /**
   * 发货地区编码
   */
  private String shipAreaCode;
  /**
   * 发货地址省 市 区
   */
  private String shipArea;
  /**
   * 发货人详细地址
   */
  private String shipAddress;
  /**
   * 录入日期
   */
  private Long inputDateTimestamp;
  /**
   * 收货时间
   */
  private Long receiptTimestamp;
  /**
   * 录单人员id
   */
  private Long operatorId;
  /**
   * 收货人姓名
   */
  private String deliName;
  /**
   * 收货人联系电话
   */
  private String deliTel;
  /**
   * 收货地区编码
   */
  private String deliAreaCode;
  /**
   * 收货地址省 市 区
   */
  private String deliArea;
  /**
   * 收货人详细地址
   */
  private String deliAddress;
  /**
   * 出库时间
   */
  private Long deliveryTimestamp;
  /**
   * 要求到货时间
   */
  private Long receiveTimestamp;
  /**
   * 订单账期
   */
  private Integer accountPeriod;
  /**
   * 物流生成状态(0：未生成物流单 1：部分生成物流单2：完成生成物流单)
   */
  private Short generatedState;
  /**
   * 发货状态(0：未发货 1：部分发货 2：完成发货)
   */
  private Short deliveryState;
  /**
   * 签收状态(0：未签收 1：部分签收 2：完成签收)
   */
  private Short collectState;
  /**
   * 商品总额
   */
  private BigDecimal goodsTotalAmount;
  /**
   * 对应对账单id
   */
  private Long statementId;
  /**
   * 我方单据图片
   */
  private String mainSrcImages;
  /**
   * 对方单据图片
   */
  private String secondSrcImages;
  /**
   * 是否已生成记录(库存记录、应收付记录等) 0:未生成 1：已生成
   */
  private Short haveRecord;
  /**
   * 订单费用表id
   */
  private Long orderExpensesBillId;
  /**
   * 其他费用
   */
  private BigDecimal otherExpenses;
  /**
   * 订单明细
   */
  protected List<SaleOrderItem> items;

}
